package com.zp.business.impl.template;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.RemoteAdministrationDictService;
import com.zp.base.api.vo.PerformFreqDictVo;
import com.zp.business.entity.template.TemplateDetail;
import com.zp.business.entity.template.bo.TemplateDetailBo;
import com.zp.business.entity.template.vo.TemplateDetailVo;
import com.zp.business.mapper.template.TemplateDetailMapper;
import com.zp.business.service.template.ITemplateDetailService;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.drug.api.vo.DrugInfoVo;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模板子表Service业务层处理
 *
 * @author zhang peng
 * @ date 2024-04-09
 */
@RequiredArgsConstructor
@Service
public class TemplateDetailServiceImpl implements ITemplateDetailService {

    static Map<String, PerformFreqDictVo> performFreqDictMap = CacheUtils.get(CacheNames.PERFORM_FREQ_DICT);
    // 药品基本信息
    static Map<String, DrugInfoVo> drugInfoVoMap = CacheUtils.get(CacheNames.DRUG_INFO);
    private final TemplateDetailMapper baseMapper;
    @DubboReference
    private RemoteAdministrationDictService administrationDictService;


    /**
     * 查询模板子表
     */
    @Override
    public TemplateDetailVo queryById (String detailId) {
        return baseMapper.selectVoById(detailId);
    }

    /**
     * 查询模板子表列表(分页)
     */
    @Override
    public TableDataInfo<TemplateDetailVo> queryPageList (TemplateDetailBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TemplateDetail> lqw = buildQueryWrapper(bo);
        Page<TemplateDetailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询模板子表列表(不分页)
     */
    @Override
    public List<TemplateDetailVo> queryList (TemplateDetailBo bo) {
        LambdaQueryWrapper<TemplateDetail> lqw = buildQueryWrapper(bo);
        List<TemplateDetailVo> templateDetailVos = baseMapper.selectVoList(lqw);
        templateDetailVos.forEach(item -> {
            item.setPerformFreqName(StringUtils.isNotBlank(item.getPerformFreq()) && CollectionUtil.isNotEmpty(performFreqDictMap)
                    ? performFreqDictMap.get(item.getPerformFreq()).getFreqDesc() : "");
            String administrationLabel = administrationDictService.getAdministrationLabel(item.getOrgId(), item.getChannel());
            item.setChannelName(administrationLabel);
            item.setSingleDosageMin(CollectionUtil.isNotEmpty(drugInfoVoMap) ?
                    drugInfoVoMap.get(item.getDrugInfoId()).getDose() : BigDecimal.valueOf(0.00));
            item.setPackageNum(CollectionUtil.isNotEmpty(drugInfoVoMap) ?
                    drugInfoVoMap.get(item.getDrugInfoId()).getPackageNum() : 2);
            item.setPerformFreqInfo(performFreqDictMap.get(item.getPerformFreq()));
        });
        return templateDetailVos;
    }

    private LambdaQueryWrapper<TemplateDetail> buildQueryWrapper (TemplateDetailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TemplateDetail> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTemplateMasterId()), TemplateDetail::getTemplateMasterId, bo.getTemplateMasterId());
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), TemplateDetail::getItemName, bo.getItemName());
        lqw.eq(StringUtils.isNotBlank(bo.getItemCode()), TemplateDetail::getItemCode, bo.getItemCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), TemplateDetail::getOrgId, bo.getOrgId());
        return lqw;
    }

    /**
     * 新增模板子表
     */
    @Override
    public Boolean insertByBo (TemplateDetailBo bo) {
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("org_id", bo.getDetailBoList().get(0).getOrgId());
        columnMap.put("template_master_id", bo.getDetailBoList().get(0).getTemplateMasterId());
        baseMapper.deleteByMap(columnMap);
        bo.getDetailBoList().forEach(detail -> {
            detail.setDelFlag("0");
            detail.setPerformFreqName(StringUtils.isNotBlank(detail.getPerformFreq()) && CollectionUtil.isNotEmpty(performFreqDictMap)
                    ? performFreqDictMap.get(detail.getPerformFreq()).getFreqDesc() : "");
            String administrationLabel = administrationDictService.getAdministrationLabel(bo.getOrgId(), detail.getChannel());
            detail.setChannelName(administrationLabel);
            detail.setIsSkin(StringUtils.equals(detail.getIsSkin(), "true") ? UserConstants.YES : UserConstants.NO);
            detail.setNoSkin(StringUtils.equals(detail.getIsSkin(), "true") ? UserConstants.NO : UserConstants.YES);
        });
        List<TemplateDetail> templateDetails = BeanUtil.copyToList(bo.getDetailBoList(), TemplateDetail.class);
        return baseMapper.insertBatch(templateDetails);

    }

    /**
     * 修改模板子表
     */
    @Override
    public Boolean updateByBo (TemplateDetailBo bo) {
        TemplateDetail update = BeanUtil.toBean(bo, TemplateDetail.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (TemplateDetail entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除模板子表
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
